package com.sywb.chuangyebao.lifecycle;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;

import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IFragment;
import org.bining.footstone.rxjava.rxbus.RxBus;

public class FragmentLifecycleCallbackImpl extends FragmentManager.FragmentLifecycleCallbacks {

    @Override
    public void onFragmentCreated(FragmentManager fm, Fragment fragment, Bundle savedInstanceState) {
        Logger.i(fragment + " onFragmentCreated");

        // 在配置变化的时候将这个 Fragment 保存下来,在 Activity 由于配置变化重建是重复利用已经创建的Fragment。
        // https://developer.android.com/reference/android/app/Fragment.html?hl=zh-cn#setRetainInstance(boolean)
        // 在 Activity 中绑定少量的 Fragment 建议这样做,如果需要绑定较多的 Fragment 不建议设置此参数,如 ViewPager 需要展示较多 Fragment
        fragment.setRetainInstance(false);

        if (fragment instanceof IFragment) {
            if (((IFragment) fragment).useRxBus()) {
                RxBus.get().register(fragment);
            }
        }
    }

    @Override
    public void onFragmentViewCreated(FragmentManager fm, Fragment fragment, View view, Bundle savedInstanceState) {
        Logger.i(fragment + " onFragmentViewCreated");

//        Bundle bundle = new Bundle();
//        ActivityBean bean = new ActivityBean();
//        Unbinder unbinder = ButterKnife.bind(fragment, view);
//        bean.setUnbinder(unbinder);
//        bundle.putSerializable("ActivityBean", bean);
//        fragment.setArguments(bundle);
    }

    @Override
    public void onFragmentViewDestroyed(FragmentManager fm, Fragment fragment) {
        Logger.i(fragment + " onFragmentViewDestroyed");

//        ActivityBean bean = (ActivityBean) fragment.getArguments().getSerializable("ActivityBean");
//        assert bean != null;
//        Unbinder unbinder = bean.getUnbinder();
//        if (unbinder != null || unbinder != Unbinder.EMPTY) {
//            unbinder.unbind();
//        }
    }

    @Override
    public void onFragmentDestroyed(FragmentManager fm, Fragment fragment) {
        Logger.i(fragment + " onFragmentDestroyed");

        // ((RefWatcher) ((IApp) f.getActivity().getApplication()).getAppComponent().extras().get(RefWatcher.class.getName())).watch(this);
        if (fragment instanceof IFragment) {
            if (((IFragment) fragment).useRxBus()) {
                RxBus.get().unregister(fragment);
            }
        }
    }
}
